package com.ruoyi.locksApi.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.locksApi.domain.WechatMiniProgramApiUser;
import com.ruoyi.locksApi.service.IWechatMiniProgramApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wechat/miniprogram")
public class WechatMiniProgramApiController {

    @Autowired
    private IWechatMiniProgramApiService wechatUserService;

    /**
     * 微信登录
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestParam String code) {
        try {
            WechatMiniProgramApiUser user = wechatUserService.handleWechatLogin(code, null, null);
            
            Map<String, Object> data = new HashMap<>();
            data.put("openid", user.getOpenid());
            data.put("phone", user.getPhone());
            
            return AjaxResult.success("登录成功", data);
        } catch (Exception e) {
            return AjaxResult.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 绑定手机号
     */
    @PostMapping("/bindPhone")
    public AjaxResult bindPhone(@RequestParam String openid, @RequestParam String code) {
        try {
            boolean success = wechatUserService.handlePhoneBinding(openid, code);
            if (success) {
                return AjaxResult.success("手机号绑定成功");
            } else {
                return AjaxResult.error("手机号绑定失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("手机号绑定失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/userInfo")
    public AjaxResult getUserInfo(@RequestParam String openid) {
        WechatMiniProgramApiUser user = wechatUserService.getByOpenId(openid);
        if (user != null) {
            return AjaxResult.success("获取成功", user);
        } else {
            return AjaxResult.error("用户不存在");
        }
    }
} 